﻿using FortuneArterial.Site.Model;
using FortuneArterial.Site.Model.System;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FortuneArterial.Site.BusinessLogicLayer.Entity
{
    public class EntityFactory
    {
        public static T CreateEntity<T>()
            where T : BaseEntity, new()
        {
            Database.Context context = new Database.Context();

            DataPrefixAttribute dataPrefixAttribute =
                (from a in typeof(T).GetCustomAttributes(true)
                 where a is DataPrefixAttribute
                 select a as DataPrefixAttribute).FirstOrDefault<DataPrefixAttribute>();

            CodeRecordInfo codeRecorder =
                (from cr in context.CodeRecordInfoSet
                 where cr.Prefix == dataPrefixAttribute.DataPrefix
                 select cr).FirstOrDefault<CodeRecordInfo>();
            if (codeRecorder == null){
                codeRecorder = new CodeRecordInfo() 
                {
                    Prefix = dataPrefixAttribute.DataPrefix,
                    Code = 0
                };

                context.CodeRecordInfoSet.Add(codeRecorder);
            }

            codeRecorder.Code++;

            T entity = new T(){
                ID = dataPrefixAttribute.DataPrefix + codeRecorder.Code.ToString().PadLeft(8 - dataPrefixAttribute.DataPrefix .Length, '0')
            };

            context.SaveChanges();

            return entity;
        }
    }
}
